package top.ffhome.game.ch04;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class TerisPanel extends JPanel implements Runnable, KeyListener {
    private int xPos = 90, yPos = -80;
    private Image iBuffer;
    private Graphics gBuffer;

    public TerisPanel() {
        Thread t = new Thread(this);
        t.start();
        setFocusable(true);
        addKeyListener(this);
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
            }
            yPos += 5;
            if (yPos > 300) {
                yPos = -80;
            }
            repaint();
        }
    }

    @Override
    public void paint(Graphics g) {
        if (iBuffer == null) {
            iBuffer = createImage(this.getSize().width, this.getSize().height);
            gBuffer = iBuffer.getGraphics();
        }
        gBuffer.setColor(getBackground());
        gBuffer.fillRect(0, 0, this.getSize().width, this.getSize().height);
        gBuffer.setColor(Color.RED);
        gBuffer.fillOval(xPos, yPos, 80, 80);
        g.drawImage(iBuffer, 0, 0, this);
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT:
                xPos -= 10;
                break;
            case KeyEvent.VK_RIGHT:
                xPos += 10;
                break;
        }
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
}
